#!/bin/bash

# 项目名称
project_name="kiwi-server"

target_dir=$(pwd)

# 获取当前时间戳
timestamp=$(date +\%Y\%m\%d_\%H\%M)

pid=$(ps ax | grep -i "${project_name}" | grep "${target_dir}" | grep java | grep -v grep | awk '{print $1}')
if [ -z "$pid" ] ; then
    echo "No ${project_name} running."
else
    echo "The ${project_name} (${pid}) is running..."
    echo "Sending shutdown request to ${project_name} (${pid})..."
    kill ${pid}

    # 等待确认进程已关闭
    max_wait_time=8
    wait_interval=2
    waited_time=0

    while [ $waited_time -lt $max_wait_time ]; do
        sleep $wait_interval
        new_pid=$(ps ax | grep -i "${project_name}" | grep "${target_dir}" | grep java | grep -v grep | awk '{print $1}')
        if [ -z "$new_pid" ] ; then
            echo "${project_name} (${pid}) has been successfully stopped."
            break
        fi
        waited_time=$((waited_time + wait_interval))
    done

    if [ $waited_time -ge $max_wait_time ]; then
        echo "Failed to stop ${project_name} (${pid}). Please check and try again."
        exit 1
    fi
fi

# 启动项目
echo "正在启动 ${project_name}"
nohup java -jar "${target_dir}/${project_name}.jar" >> "${project_name}_${timestamp}.log" 2>&1 & echo "${project_name} 启动中，请稍后..." && disown

# 等待启动日志中出现 "Server startup" 关键字
max_startup_wait_time=120
startup_wait_interval=5
startup_waited_time=0

while [ $startup_waited_time -lt $max_startup_wait_time ]; do
    sleep $startup_wait_interval
    if grep -q "Server startup" "${project_name}_${timestamp}.log"; then
        echo "${project_name} has started successfully."
        exit 0
    fi
    startup_waited_time=$((startup_waited_time + startup_wait_interval))
done

echo "Failed to start ${project_name}. Please check the logs for errors."
exit 1